import argparse
from pathlib import Path

import parse
import save


def process_folder(input_dir: str, output_dir: str) -> None:
    """处理文件夹中的所有.lsp文件"""
    input_path = Path(input_dir)
    output_path = Path(output_dir)
    
    # 确保输出目录存在
    output_path.mkdir(parents=True, exist_ok=True)
    
    # 查找所有.lsp文件
    lsp_files = list(input_path.glob("*.lsp"))
    
    if not lsp_files:
        print(f"警告：目录 {input_dir} 中未找到.lsp文件")
        return
    
    for lsp_file in lsp_files:
        try:
            # 读取文件内容
            with open(lsp_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 提取数据
            data = parse.extract_data(content)

            # 构建输出路径
            output_file = output_path / f"{lsp_file.stem}.xlsx"
            
            # 保存为Excel
            save.save_to_excel_simple(data, output_file)
            print(f"✅ 处理完成: {lsp_file.name} -> {output_file}")
        
        except Exception as e:
            print(f"❌ 处理失败: {lsp_file.name} - {str(e)}")

if __name__ == "__main__":

    # 设置命令行参数
    parser = argparse.ArgumentParser(description="批量解析.lsp文件并保存为Excel")
    parser.add_argument(
        "-i", "--input", 
        required=False,
        help="输入文件夹路径(包含.lsp文件)"
    )
    parser.add_argument(
        "-o", "--output", 
        default="output_excels",
        help="输出文件夹路径(默认: 当前目录下的output_excels)"
    )

    # 解析命令行参数
    args = parser.parse_args()

    # 如果指定了输入文件夹
    if args.input:
        process_folder(args.input, args.output)
    else:
        # 使用示例文本进行测试（保持原有逻辑）
        sample_text = '''
        ((AND (= OI 0) 
              (= CL "X10CrWMoVNb9-2")
              (<= (ATOF YL) 30.8)
              (<= (ATOF WD) 610)
              (= WJ "235")
              (= BH "69")
         )
         (LIST "235x69" "235x69" 6.66 "557.4" "P30.8T610A31SI" 3.1 260)
        )
        ((AND (= OI 0) 
              (= CL "X10CrWMoVNb9-2")
              (<= (ATOF YL) 30.8)
              (<= (ATOF WD) 610)
              (= WJ "254")
              (= BH "75")
         )
         (LIST "254x75" "254x75" "655.8" "P30.8T610A31SI")
        )
        ((AND (= OI 0) 
              (= CL "X10CrWMoVNb9-2")
              (<= (ATOF YL) 30.8)
              (<= (ATOF WD) 610)
              (= WJ "273")
              (= BH "78")
         )
         (LIST "273x78" "273x78" "729.7" "P30.8T610A31SI")
        )
        '''
        data = parse.extract_data(sample_text)
        save.save_to_excel_simple(data, "output.xlsx")
        print("测试数据已保存到 output.xlsx")
